# coding: utf-8
import codecs
from hashlib import blake2b as hash_
import pathlib
import time
import threading
import wx
from wx.core import SpinButton   #wxpython
import wx.xrc
import wx.grid as grid
import math
import os
import sys
import sqlite3
import logging
import csv
import shutil
from threading import Thread
from pubsub import pub #pypubsub
from copy_gui import *

class P2(MyPanel2):
    def __init__(self,parent):
        super().__init__(parent)  

class D1(MyFrame2):
    
    def __init__(self,parent):
        super().__init__(parent)    
        self.Bind(wx.EVT_CLOSE, self.__onClose) # (Allows frame's title-bar close to work)
        self.CenterOnParent()
        self.GetParent().Enable(False)
        P2(self)
        self.Show(True)

        self.__eventLoop = wx.EventLoop()
        self.__eventLoop.Run()

    def __onClose(self, event):
        self.GetParent().Enable(True)
        self.__eventLoop.Exit()
        self.Destroy()

class F1(MyFrame1):
    
    def __init__(self,parent):
        global m_statusBar1
        super().__init__(parent)
        m_statusBar1=self.m_statusBar1

class P1(MyPanel1):
    def __init__(self, parent):
        global SourcePath
        global TargetPath
        self.dig1=None
        super().__init__(parent)
        SourcePath=pathlib.Path(self.m_dirSource.GetPath())
        TargetPath=pathlib.Path(self.m_dirTarget.GetPath())
        pub.subscribe(self.updateSetStatusText,"uptext")
        pub.subscribe(self.updateGauge,"upgauge")
    
    def startCopy( self, event ):
        global m_statusBar1
        global SourcePath
        global TargetPath
        global TotalSize
        TotalSize=0
        list=[]
        self.m_gauge3.SetValue( 0 )
        m_statusBar1.SetStatusText("asdf")
        filelist_t=self.m_textCtrl1.GetValue()
        filelist=filelist_t.split("\n")
        for file in filelist:
            if(file ==""):
                continue
            file=file.strip('\\')
            file=file.strip("/")
            S_path=SourcePath/file
            if(S_path.is_file()):
                TotalSize=TotalSize+os.path.getsize(str(S_path))
                list.append(file)
            else:
                wx.MessageBox(f"{str(S_path)} 源文件不存在","文件错误",wx.OK | wx.ICON_ERROR)
                print(f"{S_path} no file")

        print(TotalSize)
        self._copy(list)

        #wx.MessageBox(filelist_t)
        event.Skip()


    def reCheck( self, event ):
        D1(self)
        event.Skip()
    def openDirSource( self, event ):
        global m_statusBar1
        global SourcePath
        SourcePath=pathlib.Path(event.GetPath())
        m_statusBar1.SetStatusText(f"源文件夹{SourcePath}")

    def openTarget( self, event ):
        global m_statusBar1
        global TargetPath
        TargetPath =pathlib.Path(event.GetPath())
        m_statusBar1.SetStatusText(f"目标文件夹{TargetPath}")


    def _copy(self,list):
        
        global SourcePath
        global TargetPath
        global completeSize
        
        for i in list:
            pass
            '''
            print(i)
            #m_statusBar1.SetStatusText(f"正在复制{str(SourcePath/i)} 到 {TargetPath}")
            #pub.sendMessage("uptext",msg=f"正在复制{str(SourcePath/i)} 到 {TargetPath}")
            wx.CallAfter(pub.sendMessage, "uptext", msg=f"正在复制{str(SourcePath/i)} 到 {TargetPath}")
            time.sleep(0.1)
            '''
        cpThread(list)

    def updateSetStatusText(self, m):
        global m_statusBar1
        m_statusBar1.SetStatusText(m)
    def updateGauge(self,v):
        global TotalSize
        global completeSize
        self.m_gauge3.SetValue(int(completeSize/TotalSize*100))
        self.m_gauge4.SetValue(v)
    
class cpThread(Thread):
    def __init__(self,list):
        self.list=list
        Thread.__init__(self)
        global nowtime
        nowtime = time.time()
        self.start()
        
    def run(self):
        global SourcePath
        global TargetPath
        global completeSize
        for i in self.list:
            print(i)
            
            #m_statusBar1.SetStatusText(f"正在复制{str(SourcePath/i)} 到 {TargetPath}")
            #pub.sendMessage("uptext",msg=f"正在复制{str(SourcePath/i)} 到 {TargetPath}")
            wx.CallAfter(pub.sendMessage, "uptext", m=f"正在复制{str(SourcePath/i)} 到 {TargetPath/i}")
            if(os.path.getsize(str(SourcePath/i))>1024*1024*50):
                threading.Thread(name='progresso', target=getPERCECENTprogress, args=(str(SourcePath/i), str(TargetPath/i))).start()
            shutil.copy2(SourcePath/i, TargetPath/i)
            #time.sleep(0.1)
            completeSize=completeSize+os.path.getsize(str(SourcePath/i))
            wx.CallAfter(pub.sendMessage, "upgauge", v=0)

def getsize(filePath):
    return os.path.getsize(filePath)

def getPERCECENTprogress(source_path, destination_path):
    time.sleep(0.1)
    if os.path.exists(destination_path):
        while os.path.getsize(source_path) != os.path.getsize(destination_path):
            #sys.stdout.write('\r')
            #percentagem = int((float(os.path.getsize(destination_path))/float(os.path.getsize(source_path))) * 100)
            wx.CallAfter(pub.sendMessage, "upgauge", v=int(os.path.getsize(destination_path)/os.path.getsize(source_path)*100))
            #print(float(os.path.getsize(destination_path)),os.path.getsize(source_path),int(os.path.getsize(destination_path)/os.path.getsize(source_path)*100))
            time.sleep(0.1)
if __name__ =="__main__":
    global m_statusBar1
    global SourcePath
    global TargetPath
    global TotalSize
    global completeSize
    completeSize = 0
    app = wx.App()
    w = F1(None)
    p = P1(w)
    w.Show()
    app.MainLoop()